<template>
  <div class="components-ranking">
    <HeadBar
      :title="$t('dataAnalysis.goodsDet')"
      :date-options="dateOptions"
      :date-type="5"
      :show-export="isAuth('flow:pay:visit:top')"
      @date-change="onDateChange"
      @export="onExport"
    />
    <div class="ranking-box">
      <div class="ranking-left-analysis">
        <div class="ranking-title">
          {{ $t("dataAnalysis.amountPaidTOP") }}
        </div>
        <el-table
          :data="payAmountTopData"
          style="width: 100%"
          height="100%"
          :header-cell-style="analysisTableHeaderClass"
          :cell-style="analysisTableCellClass"
        >
          <el-table-column
            :label="$t('home.rank')"
            type="index"
            width="100"
          />
          <el-table-column
            :label="$t('product.prodName')"
            type="index"
            width="500"
          >
            <template #default="scope">
              <div
                class="table-cell-con cursor-p"
                @click="handleShowProdDetailPop(scope.row.prodId)"
              >
                <div class="table-cell-image">
                  <ImgShow :src="scope.row.pic" />
                </div>
                <span class="table-cell-text">{{ scope.row.prodName }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('home.payAmount')"
            align="center"
            prop="payAmount"
          />
        </el-table>
      </div>
      <div class="ranking-right">
        <div class="ranking-title">
          {{ $t("dataAnalysis.visitorsTop") }}
        </div>
        <el-table
          :header-cell-style="analysisTableHeaderClass"
          :cell-style="analysisTableCellClass"
          :data="visitorTopData"
          height="100%"
          style="width: 100%"
        >
          <el-table-column
            :label="$t('home.rank')"
            type="index"
            width="100"
          />
          <el-table-column
            :label="$t('product.prodName')"
            width="410"
          >
            <template #default="scope">
              <div
                class="table-cell-con cursor-p"
                @click="handleShowProdDetailPop(scope.row.prodId)"
              >
                <div class="table-cell-image">
                  <ImgShow :src="scope.row.pic" />
                </div>
                <span class="table-cell-text">{{ scope.row.prodName }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('dataAnalysis.numberOfVisitors')"
            prop="visitorNum"
            align="center"
          />
          <el-table-column
            :label="$t('dataAnalysis.vToP')"
            align="right"
            prop="visitorToPayRate"
          >
            <template #default="scope">
              <span style="padding-right:10px">{{ parseFloat(scope.row.visitorToPayRate * 100).toFixed(2) + '%' }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 商品详情弹窗 -->
    <prod-detail
      v-if="prodDetailVisiable"
      ref="prodDetailRef"
      @handle-hide-pop="handleHidePop"
    />
  </div>
</template>

<script setup>
import { ElLoading, ElMessage } from 'element-plus'
import { isAuth } from '@/utils'
import HeadBar from './head-bar.vue'
import ProdDetail from '../../components/prod-detail.vue'

const dateOptions = [
  {
    label: $t('dataAnalysis.nearly7'),
    value: 5
  },
  {
    label: $t('dataAnalysis.nearly30'),
    value: 6
  },
  {
    label: $t('dataAnalysis.naturalMonth'),
    value: 3
  }
]

// 时间更新
// 2:近七天 3:近30天 5:自然月
let dateType = 2
let dateRange = []
const onDateChange = (data) => {
  dateRange = data.dateRange
  let tempType
  switch (data.timeType) {
    case 5:
      tempType = 2
      break
    case 6:
      tempType = 3
      break
    case 3:
      tempType = 5
      break
  }
  dateType = tempType
  getPayAmountTop()
}

/**
 * 获取支付金额TOP
 */
const payAmountTopData = ref([]) // 支付金额TOP
const visitorTopData = ref([]) // 访问top
const getPayAmountTop = () => {
  http({
    url: http.adornUrl('/platform/prodAnalysis/getPayAmountTop'),
    method: 'get',
    params: http.adornParams(
      {
        current: 1,
        size: 6,
        dateType,
        startTime: dateRange[0],
        endTime: dateRange[1]
      }
    )
  }).then(({ data }) => {
    if (data) {
      payAmountTopData.value = data.payAmounts
      visitorTopData.value = data.visitors
    }
  })
}

/**
 * 展示商品详情
 * @param {Number} prodId 商品id
 */
const prodDetailRef = ref(null)
const prodDetailVisiable = ref(false)
const handleShowProdDetailPop = (prodId) => {
  prodDetailVisiable.value = true
  nextTick(() => {
    prodDetailRef.value?.init(prodId)
  })
}
const handleHidePop = () => {
  prodDetailVisiable.value = false
}

const onExport = () => {
  const loading = ElLoading.service({
    lock: true,
    target: '.components-ranking',
    customClass: 'export-load',
    background: 'transparent',
    text: $t('shop.exportIng')
  })
  http({
    url: http.adornUrl('/platform/prodAnalysis/payAmountTopExport'),
    method: 'get',
    params: http.adornParams({
      current: 1,
      size: 6,
      dateType,
      startTime: dateRange[0],
      endTime: dateRange[1]
    }),
    responseType: 'blob'
  }).then(({ data }) => {
    loading.close()
    const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
    const fileName = $t('dataAnalysis.commodityRanking') + '.xlsx'

    const elink = document.createElement('a')
    if ('download' in elink) { // 非IE下载
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL 对象
      document.body.removeChild(elink)
    } else { // IE10+下载
      navigator.msSaveBlob(blob, fileName)
    }
    ElMessage({
      message: $t('shop.exportSuccess'),
      type: 'success',
      duration: 1500
    })
  }).catch(() => {
    loading.close()
  })
}

const analysisTableHeaderClass = computed(() => {
  return {
    height: '64px',
    background: '#FFF',
    color: '#666666',
    'font-weight': '500',
    border: 'none',
    'word-break': 'break-word',
    '-webkit-line-clamp': '2',
    '-webkit-box-orient': 'vertical',
    overflow: 'hidden'
  }
})
const analysisTableCellClass = computed(() => {
  return {
    height: '64px', padding: '8px 0', color: '#000'
  }
})
</script>

<style lang="scss" scoped>
.components-ranking {
  .ranking-box {
    padding: 0;
    margin-top: 10px;
    display: flex;
    flex-direction: unset;
    justify-content: space-between;
    width: 100%;
    .ranking-left-analysis,
    .ranking-right {
      height: 500px;
      width: calc(50% - 10px);
      display: flex;
      flex-direction: column;
      box-sizing: border-box;
      border: 1px solid #EAF0F4;
      border-bottom: none;
    }
    .ranking-title {
      font-size: 16px;
      font-weight: 400;
      line-height: 50px;
      height: 50px;
      color: #463333;
      padding-left: 20px;
      margin-bottom: 10px;
      background: #F7F8FA;
    }
    // 图片 + 文本
    .table-cell-con {
      display: flex;
      align-items: center;
      &.cursor-p {
        cursor: pointer;
      }
      .table-cell-image {
        overflow: hidden;
        width: 42px;
        height: 42px;
        margin-right: 10px;
        // eslint-disable-next-line vue-scoped-css/no-unused-selector
        img {
          display: block;
          width: 100%;
          height: 100%;
          object-fit: contain;
        }
      }
      .table-cell-text {
        flex: 1;
        text-overflow: ellipsis;
        word-break: break-word;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
        line-height: 20px;
      }
    }
  }
}
</style>
